// pages/live/detail/detail.js
import {
    HTTP
} from '../../../utils/http.js'
let ajax = new HTTP()
const app = getApp()
var socketOpen = false
var SocketTask, url
var phoneWidth = 0
let confirmsend = false

Page({
    data: {
        isLike: 0,
        isLove: 0,
        likeNum: 0,
        loveNum: 0,
        scrollTop: 0,
        liveUrl: "",
        username: "",
        userpic: "",
        quanpingShow: true,
        titleArr: [{
                imgUrl: "../images/002.png",
                text: "介绍",
                id: 0
            },{
                imgUrl: "../images/001.png",
                text: "评论",
                id: 1
            },{
                imgUrl: "../images/006.png",
                text: "邀请排行榜",
                id: 2 
            }
        ],
        chatArr: [],
        currentTab: 0,
        winHeight: "",
        canvasWidth: "",
        canvasHeight: "",
        inputValue: "",
        id: "",
        liveName: "",
        liveInfo: "",
        fullScreenFlag: false,
        liveDirection: "vertical",
        barrageArr: [],
        inviteList: [],
        sharePic: "",
        shareFlag: false,
        canvasHidden: true,
        bannerpic: "",
        videourl: "",
        isBegin: true,
        isLoading: false,
        countdownText: "",
        mutedFlag: false,
        returnFlag: false
    },
    onInputFoc (event) {
        confirmsend = true
    },
    // 点击列表
    switchNav(event) {
        let cur = event.currentTarget.dataset.current
        if (this.data.currentTab === cur) {
            return false
        } else {
            this.setData({
                currentTab: cur
            })
        }
    },
    // 左右滑动
    switchTab(event) {
        this.setData({
            currentTab: event.detail.current
        })
    },
    // 发送
    onInputTap(event) {
        if (confirmsend) {
            confirmsend = false
            let value = event.detail.value
            let name = app.globalData.userInfo.nickName
            let data = {
                name: name,
                text: value
            }
            if (socketOpen) {
                console.log(data)
                this.sendSocketMessage(data)
                this.data.chatArr.push({
                    name: name,
                    text: value
                })
                this.setData({
                    scrollTop: this.data.chatArr.length * 100,
                    inputValue: "",
                    chatArr: this.data.chatArr
                })
            }
        }
    },
    // 分享
    onShare () {
        this.setData({
            quanpingShow: false,
            shareFlag: false
        })
    },
    // 生成海报
    onCreate () {
        wx.showLoading({
            title: '正在生成海报',
        })
        let that = this
        ajax.request({
            url: "weixin/getqrcode",
            data: {
                url: 'pages/live/detail/detail',
                actid: this.data.id,
                memberid: app.globalData.memberid
            },
            success: (res) => {
                wx.getImageInfo({
                    src: res,
                    success: (res) => {
                        that.drawImg(res.path)
                    }
                })
            }
        })
    },
    // 绘制海报
    drawImg (res) {
        let that = this
        this.setData({
            canvasHidden: false
        })
        let context = wx.createCanvasContext('share')
        context.clearRect(0, 0, that.data.canvasWidth, that.data.canvasHeight * .8)
        context.setFillStyle('#fff')
        context.fillRect(0, 0, that.data.canvasWidth, that.data.canvasHeight * .8)
        // 绘制个人信息
        let avatar = that.data.userpic
        let name = that.data.username
        context.drawImage(avatar, 20, that.data.canvasHeight * 0.05 * .8, 50, 50)
        context.setFontSize(16)
        context.setFillStyle("#000")
        context.fillText(name, 86, that.data.canvasHeight * 0.05 * .8 + 20)
        context.setFontSize(12)
        context.setFillStyle("#888")
        context.fillText("邀您观看", 86, that.data.canvasHeight * 0.05 * .8 + 40)
        // 绘制直播图片
        let liveImg = that.data.bannerpic
        console.log(liveImg)
        context.drawImage(liveImg, (that.data.canvasWidth - that.data.canvasWidth * .8 ) / 2, that.data.canvasHeight * 0.25 * .8, that.data.canvasWidth * .8, that.data.canvasHeight * 0.26 * .8)
        // 绘制直播名称
        let title = that.data.liveName
        context.setFontSize(16)
        context.setFillStyle("#000")
        context.fillText(title, (that.data.canvasWidth - context.measureText(title).width) / 2, that.data.canvasHeight * 0.25 + that.data.canvasHeight * 0.26 * .8 * .8 + 30)
        // 绘制直播状态
        context.setFontSize(12)
        context.setFillStyle("#888")
        let statusText = that.data.isBegin ? "正在直播" : "即将开始"
        context.fillText(statusText, (that.data.canvasWidth - context.measureText(statusText).width) / 2, that.data.canvasHeight * 0.25 + that.data.canvasHeight * 0.26 * .8 * .8 + 56)
        // 绘制二维码
        context.drawImage(res, (that.data.canvasWidth - that.data.canvasWidth * .32 * .8) / 2, that.data.canvasHeight * .72 * .8, that.data.canvasWidth * .32 * .8, that.data.canvasWidth * .32 * .8)
        // 绘制备注
        context.setFontSize(12)
        context.setFillStyle("#888")
        context.fillText("长按屏幕识别小程序码观看直播", (that.data.canvasWidth - context.measureText("长按屏幕识别小程序码观看直播").width) / 2, that.data.canvasHeight * .72 * .8 + that.data.canvasWidth * .32 * .8 + 20)
        // 生成图片
        context.draw(false, function () {
            let pixelRatio = that.getPixelRatio()
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: that.data.canvasWidth,
                height: that.data.canvasHeight,
                destWidth: that.data.canvasWidth * pixelRatio,
                destHeight: that.data.canvasHeight * pixelRatio * .8,
                canvasId: 'share',
                quality: .7,
                success: a => {
                    that.setData({
                        shareFlag: true,
                        canvasHidden: true
                    })
                    let imgArr = []
                    imgArr.push(a.tempFilePath)
                    wx.previewImage({
                        current: '0',
                        urls: imgArr
                    })
                    wx.hideLoading()
                }
            })
        })
    },
    // 获取屏幕分辨率
    getPixelRatio () {
        let pixelRatio = 0
        wx.getSystemInfo({
            success: function (res) {
                pixelRatio = res.pixelRatio
            },
            fail: function () {
                pixelRatio = 0
            }
        })
        return pixelRatio
    },
    // 关闭分享
    closeShare () {
        this.setData({
            quanpingShow: true
        })
    },
    shareWX () {
        this.data.quanpingShow = false
        wx.showShareMenu({
            withShareTicket: this.data.quanpingShow
        })
    },
    // 转发 
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
        this.data.quanpingShow = true
        this.setData({
            quanpingShow: this.data.quanpingShow
        })
        return {
            title: this.data.liveName,
            imageUrl: this.data.bannerpic,
            path: '/pages/live/detail/detail?scene=frommemberid_' + app.globalData.memberid + '-actid_' + this.data.id
        }
    },
    // 收藏
    onLoveTap(event) {
        let isLove
        let loveNum = this.data.loveNum
        if (this.data.isLove === 1) {
            // 取消收藏        
            isLove = 0
            loveNum--
        } else {
            // 收藏
            isLove = 1
            loveNum++
        }
        wx.showToast({
            title: isLove === 1 ? '收藏成功' : '取消成功',
            icon: "success",
            duration: 1500
        })
        this._getLoveInfo(this.data.id, app.globalData.memberid)
        this.setData({
            isLove: isLove,
            loveNum: loveNum
        })
    },
    // 点赞
    onLikeTap(event) {
        let isLike
        let likeNum = this.data.likeNum
        if (this.data.isLike === 1) {
            // 取消点赞
            isLike = 0
            likeNum--
        } else {
            // 点赞
            isLike = 1
            likeNum++
        }
        wx.showToast({
            title: isLike === 1 ? '点赞成功' : '取消成功',
            icon: "success",
            duration: 1500
        })
        this._getLikeInfo(1, this.data.id, app.globalData.memberid)
        this.setData({
            isLike: isLike,
            likeNum: likeNum
        })
    },
    // 发送礼物
    onGiftTap(event) {
        wx.showToast({
            title: '打赏功能暂未开放，敬请期待',
            icon: 'none'
        })
    },
    returnIndex () {
        wx.switchTab({
            url: '/pages/live/live',
        })
    },
    // 加载页面
    onLoad(options) {
        wx.showLoading({
            title: '加载中',
        })
        // 转发进入
        if (options.scene) {
            let ret = options.scene.split("-")
            let id = ret[1].split("_")[1]
            this.setData({
                id: id,
                returnFlag: true
            })
            if (wx.getStorageSync("userInfo") == null || wx.getStorageSync("userInfo") === "") {
                wx.setStorageSync("flag", true)
                wx.setStorageSync("detailid", this.data.id)
                wx.reLaunch({
                    url: '/pages/welcome/welcome',
                })
                return
            }
            app.globalData.userInfo = wx.getStorageSync("userInfo")
            if (app.globalData.openid) {
                let openid = app.globalData.openid
                ajax.request({
                    url: "weixin/getinvite",
                    method: "POST",
                    data: {
                        scene: options.scene,
                        openid: openid
                    },
                    success: (res) => {
                        console.log(res)
                    }
                })
            }
            app.openidReadyCallback = (res) => {
                if (res != "") {
                    let openid = app.globalData.openid
                    console.log("openid:" + openid)
                    ajax.request({
                        url: "weixin/getinvite",
                        method: "POST",
                        data: {
                            scene: options.scene,
                            openid: openid
                        },
                        success: (res) => {
                            console.log(res)
                        }
                    })
                }
            }
        } else {
            let id = options.id
            this.setData({
                id: id
            })
        }
        url = "wss://www.xlroader.com/wss/" + this.data.id
        this.setData({
            username: app.globalData.userInfo.nickName,
            userpic: app.globalData.userInfo.avatarUrl
        })
        wx.getImageInfo({
            src: this.data.userpic,
            success: (res) => {
                this.setData({
                    userpic: res.path
                })
            }
        })
        app.memberidReadyCallback = (res) => {
            if (res != "") {
                let memberid = app.globalData.memberid
                console.log("memberid:" + memberid)
                this._getLiveUrl(this.data.id, memberid)
                this._getInviteList(this.data.id, memberid)
            }
        }
        let memberid = app.globalData.memberid
        console.log("memberid:" + memberid)
        this._getLiveUrl(this.data.id, memberid)
        this._getInviteList(this.data.id, memberid)
        // 获取聊天区域的高度
        wx.getSystemInfo({
            success: (res) => {
                let clientHeight = res.windowHeight
                let clientWidth = res.windowWidth
                let rpxR = 750 / clientWidth
                let calc = clientHeight * rpxR
                phoneWidth = calc
                this.setData({
                    winHeight: calc - 490,
                    canvasWidth: clientWidth,
                    canvasHeight: clientHeight
                })
            },
        })
    },
    // 打开页面
    onShow() {
        this.setData({
            mutedFlag: false
        })
        if (!socketOpen && app.globalData.userInfo != null) {
            this.webSocket()
        }
    },
    // 页面关闭
    onUnload() {
        SocketTask.close({
            reason: this.data.id
        })
    },
    // 页面卸载
    onHide() {
        if (!this.data.isBegin) {
            this.setData({
                mutedFlag: true
            })
        }
        SocketTask.close({
            reason: this.data.id
        })
    },
    webSocket() {
        // 创建Socket
        SocketTask = wx.connectSocket({
            url: url,
            method: 'post',
            success: function(res) {
                console.log('WebSocket连接创建', res)
            }
        })
        // 监听Socket打开
        SocketTask.onOpen(res => {
            socketOpen = true
            console.log('监听 WebSocket 连接打开事件。', res)
        })
        // 监听Socket发送消息
        SocketTask.onMessage(res => {
            console.log('发送了一条消息')
            res.data = JSON.parse(res.data)
            console.log(res.data)
            res = res.data
            if (res.msgtype == "msgcontent" && res.actid == this.data.id) {
                // if (this.data.fullScreenFlag) {
                    // 字体颜色随机
                    let textColor = "rgb(" + parseInt(Math.random() * 256) + "," + parseInt(Math.random() * 256) + "," + parseInt(Math.random() * 256) + ")"
                    // doommList.push(new Doomm(res.text, Math.ceil(Math.random() * 40), 5, '#fff'))
                    // this.setData({
                    //     barrageArr: doommList
                    // })
                // } else {
                //     this.setData({
                //         barrageArr: []
                //     })
                // }
                this.data.chatArr.push({
                    name: res.name,
                    text: res.text
                })
                console.log(this.data.chatArr)
                this.setData({
                    chatArr: this.data.chatArr,
                    scrollTop: this.data.chatArr.length * 100
                })
            }
        })
        // 监听Socket关闭
        SocketTask.onClose(res => {
            console.log('关闭 WebSocket 连接。')
            socketOpen = false
        })
    },
    // 发送数据
    sendSocketMessage(msg) {
        msg.id = this.data.id,
        // console.log("send:" + memberid)
        msg.memberid = app.globalData.memberid
        SocketTask.send({
            data: JSON.stringify(msg)
        }, (res) => {
            console.log(res)
        })
    },
    statechange(e) {
        // console.log('live-player code:', e.detail.code)
    },
    liveStatus (e) {
        
    },
    // 播放错误
    error(e) {
        // console.error('live-player error:', e.detail.errMsg)
    },
    onReady() {
        this.PlayerCtx = wx.createLivePlayerContext('myplayer')
    },
    // 全屏
    fullScreen() {
        let that = this
        let videoHeight = wx.getSystemInfoSync().windowHeight
        let fullScreenFlag = that.data.fullScreenFlag
        if (fullScreenFlag) {
            fullScreenFlag = false
        } else {
            fullScreenFlag = true
        }
        if (fullScreenFlag) {
            //全屏
            that.PlayerCtx.requestFullScreen({
                success: res => {
                    that.setData({
                        fullScreenFlag: fullScreenFlag,
                        liveDirection: "horizontal"
                    });
                },
                fail: res => {
                    console.log('fullscreen fail')
                }
            })
        } else {
            //缩小
            that.PlayerCtx.exitFullScreen({
                success: res => {
                    that.setData({
                        fullScreenFlag: fullScreenFlag,
                        liveDirection: "vertical"
                    });
                },
                fail: res => {
                    console.log('exit fullscreen success')
                }
            })
        }
    },
    // 直播退出全屏
    bindfullscreenchange (event) {
        if (!event.detail.fullScreen) {
            this.setData({
                fullScreenFlag: false,
                liveDirection: "vertical"
            })
        }
    },
    // 倒计时
    countdowm(timestamp) {
        let self = this
        let timer = setInterval(function () {
            let nowTime = new Date()
            let endTime = new Date(timestamp * 1000)
            let t = endTime.getTime() - nowTime.getTime()
            if (t > 0) {
                let day = Math.floor(t / 86400000)
                let hour = Math.floor((t / 3600000) % 24)
                let min = Math.floor((t / 60000) % 60)
                let sec = Math.floor((t / 1000) % 60)
                hour = hour < 10 ? "0" + hour : hour
                min = min < 10 ? "0" + min : min
                sec = sec < 10 ? "0" + sec : sec
                let format = ''
                if (day > 0) {
                    format = `${day}天${hour}小时${min}分${sec}秒`
                }
                if (day <= 0 && hour > 0) {
                    format = `${hour}小时${min}分${sec}秒`
                }
                if (day <= 0 && hour <= 0) {
                    format = `${min}分${sec}秒`
                }
                self.setData({
                    countdownText: format
                })
            } else {
                clearInterval(timer)
                self.setData({
                    isBegin: true
                })
                self._callback()
            }
        }, 1000)
    },
    _callback() {
        if (this.callback && this.callback instanceof Function)        {
            this.callback(...this)
        }
    },
    // 请求邀请榜
    _getInviteList (id, memberid) {
        ajax.request({
            url: "activelist/invitelist",
            data: {
                id: id,
                memberid: memberid
            },
            success: (res) => {
                res = res.data
                this.setData({
                    inviteList: res
                })
            }
        })
    },
    // 获取直播地址
    _getLiveUrl(id, memberid) {
        ajax.request({
            url: "activelist/read",
            data: {
                id: id,
                memberid: memberid
            },
            success: (res) => {
                res = res.data
                console.log(res)
                if (res.status == 1) {
                    this.setData({
                        isBegin: false
                    })
                    this.countdowm(res.start)
                }
                let liveUrl = "rtmp://" + res.pulldomain + "/" + res.app + "/" + res.stream
                this.setData({
                    isLoading: true,
                    isLike: res.hasprize,
                    isLove: res.hascollect,
                    likeNum: res.prizenum,
                    loveNum: res.collectnum,
                    liveUrl: liveUrl,
                    liveName: res.name,
                    liveInfo: res.summary.replace(/\<img/gi, '<img style="max-width:100%;height:auto" '),
                    bannerpic: res.pic,
                    videourl:res.videourl
                })
                wx.hideLoading()
                wx.getImageInfo({
                    src: this.data.bannerpic,
                    success: (res) => {
                        this.setData({
                            bannerpic: res.path
                        })
                    }
                })
            }
        })
    },
    // 请求点赞
    _getLikeInfo(index, id, memberid) {
        ajax.request({
            url: "actprizelist",
            method: "POST",
            data: {
                prizetype: index,
                actid: id,
                memberid: memberid
            }
        })
    },
    // 请求收藏
    _getLoveInfo(id, memberid) {
        ajax.request({
            url: "collectlist",
            method: "POST",
            data: {
                reltype: 1,
                relid: id,
                memberid: memberid
            },
            success: (res) => {
            }
        })
    }
})